package com.larry.tinyweb.core;


import com.larry.tinyweb.core.annotation.RmAnnotationHandler;
import com.larry.tinyweb.plugin.Plugin;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by larry on 16/9/20.
 * @author larry
 * Action注解路由
 */
public class ActionRouter implements Router,Plugin {
    private RmAnnotationHandler rmAnnotationHandler = null;

    public ActionRouter() {
        rmAnnotationHandler = new RmAnnotationHandler();
        rmAnnotationHandler.resolve();
    }

    @Override
    public void route(RequestEntity requestEntity) throws Exception {
        if (requestEntity.hasRoute()) return;

        String routerName = getRouterName(requestEntity.getRequest());
        if (routerName == null) return;
        else rmAnnotationHandler.map(requestEntity);

        requestEntity.routed();
    }

    private String getRouterName(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        if (servletPath.indexOf("?") > -1 ) servletPath = servletPath.substring(0, servletPath.lastIndexOf("?"));
        if (servletPath.lastIndexOf(".") > -1) return null;

        String substring = servletPath.substring(1);
        String[] ss = substring.split("/");
        if (ss.length == 0) return null;
        else return ss[0];
    }

    @Override
    public void plugin(RequestEntity requestEntity) throws Exception {
        route(requestEntity);
    }
}
